/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.kl.bf.service.basic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.entity.basic.DataDetail;
import org.kl.bf.entity.basic.DataRole;
import org.kl.bf.entity.basic.Function;
import org.kl.bf.entity.basic.Menu;
import org.kl.bf.entity.basic.Role;
import org.kl.bf.entity.basic.User;
import org.kl.bf.utils.BasicConstants;
import org.kl.auditsupervision.entity.fnd.Org;
import org.kl.auditsupervision.service.fnd.OrgService;
import org.springside.modules.utils.Encodes;

import com.google.common.base.Objects;

public class ShiroDbRealm extends AuthorizingRealm {

	protected AccountService accountService;
	protected MenuService menuService;
	protected CodeValuesService codeValuesService;
	protected OrgService orgService;

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = accountService.findUserByLoginNo(token.getUsername());
		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}
		byte[] salt = Encodes.decodeHex(user.getSalt());
		String deptId = user.getEmployee() != null && user.getEmployee().getOrg() != null ? user.getEmployee().getOrg().getId() : "";
		String deptName = "";
		String deptCode = "";
		String rootDeptCode = "";
		if (user.getEmployee() != null && user.getEmployee().getOrg() != null) {
			Org org = user.getEmployee().getOrg();
			deptName = org.getOrgName();
			deptCode = org.getOrgNo();
			rootDeptCode = orgService.getOne(org.getRootOrgId()).getOrgNo();
		}
		List<String> roleNoList = new ArrayList<String>();
		for (Role role : user.getRoleSet()) {
			roleNoList.add(role.getRoleNo());
		}

		Map<String, String> dataRoleMap = new HashMap<>();
		List<CodeValues> cvList = codeValuesService.findByTableCode(BasicConstants.TABLECODE_DATATYPE);
		if (cvList != null) {
			for (CodeValues cv : cvList) {// 防止没有给用户配置数据角色而导致IN搜索失效
				dataRoleMap.put(cv.getCodeName(), "null,");
			}
		}
		for (DataRole dataRole : user.getDataRoleSet()) {
			for (DataDetail dataDetail : dataRole.getDataDetailSet()) {
				if (dataRoleMap.containsKey(dataDetail.getDataType().getCodeName())) {
					if (!dataRoleMap.get(dataDetail.getDataType().getCodeName()).contains(dataDetail.getDataName())) {
						String str = dataRoleMap.get(dataDetail.getDataType().getCodeName()) + "," + dataDetail.getDataName();
						dataRoleMap.put(dataDetail.getDataType().getCodeName(), str);
					}
				} else {
					dataRoleMap.put(dataDetail.getDataType().getCodeName(), dataDetail.getDataName());
				}
			}
		}
		return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginNo(), user.getTrueName(), deptId,deptCode,rootDeptCode, deptName,
				roleNoList, dataRoleMap, user.getSysManager()), user.getPassword(), ByteSource.Util.bytes(salt), getName());
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		User user = accountService.findUserByLoginNo(shiroUser.loginName);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(getPermissions(user));
		info.addRoles(shiroUser.roleNoList);
		return info;
	}

	private List<String> getPermissions(User user) {
		List<String> permissions = new ArrayList<String>();
		if (user.getSysManager() == null || user.getSysManager() != 1) {
			for (Role role : user.getRoleSet()) {
				for (Function function : role.getRoleFunctions()) {
					function.setMenu(menuService.getMenu(function.getMenu().getId()));
					if (function.getMenu() != null && StringUtils.isNotBlank(function.getMenu().getController())) {
						permissions.add(function.getMenu().getController() + ":" + function.getFunctionNo());// 菜单的功能
						if (StringUtils.isNotBlank(function.getOtherRights())) {
							permissions.addAll(Arrays.asList(StringUtils.split(function.getOtherRights(), ",")));// 功能的而外权限
						}
					}
					if (StringUtils.isNotBlank(function.getMenu().getOtherRights())) {
						permissions.addAll(Arrays.asList(StringUtils.split(function.getMenu().getOtherRights(), ",")));
					}
				}
			}
		} else {
			List<Menu> menuList = menuService.getAllMenu();
			for (Menu menu : menuList) {
				if (StringUtils.isNotBlank(menu.getController())) {
					permissions.add(menu.getController() + ":*");
					for (Function function : menu.getFunctions()) {
						if (StringUtils.isNotBlank(function.getOtherRights())) {
							permissions.addAll(Arrays.asList(StringUtils.split(function.getOtherRights(), ",")));// 功能的而外权限
						}
					}
				}
				if (StringUtils.isNotBlank(menu.getOtherRights())) {
					permissions.addAll(Arrays.asList(StringUtils.split(menu.getOtherRights(), ",")));// 功能的而外权限
				}
			}
		}
		return permissions;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(AccountService.HASH_ALGORITHM);
		matcher.setHashIterations(AccountService.HASH_INTERATIONS);

		setCredentialsMatcher(matcher);
	}

	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public void setCodeValuesService(CodeValuesService codeValuesService) {
		this.codeValuesService = codeValuesService;
	}
	
	public void setOrgService(OrgService orgService) {
		this.orgService = orgService;
	}

	/**
	 * 自定义Authentication对象，使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public String id;
		public String loginName;
		public String name;
		public String deptName;
		public String deptId;
		public String deptCode;// 科室编码
		public String rootDeptCode;// 一级科室编码
		public List<String> roleNoList;
		public Integer sysManager;
		public String lastName = "";// 上一个身份的姓名
		public Map<String, String> dataRoleMap;
		public boolean isRunas = false;
		
		public ShiroUser(String id, String loginName, String name, String deptId,String deptCode,String rootDeptCode,String deptName, List<String> roleNoList,
				Map<String, String> dataRoleMap, Integer sysManager) {
			super();
			this.id = id;
			this.loginName = loginName;
			this.name = name;
			this.deptName = deptName;
			this.deptId = deptId;
			this.deptCode = deptCode;
			this.rootDeptCode = rootDeptCode;
			this.roleNoList = roleNoList;
			this.dataRoleMap = dataRoleMap;
			this.sysManager = sysManager;

		}

		public ShiroUser(String id, String loginName, String name, String deptId,String deptCode, String rootDeptCode,String deptName, List<String> roleNoList,
				Map<String, String> dataRoleMap, Integer sysManager, String lastName, boolean isRunas) {
			this(id, loginName, name, deptId,deptCode,rootDeptCode, deptName, roleNoList, dataRoleMap, sysManager);
			this.lastName = lastName;
			this.isRunas = isRunas;
		}

		public ShiroUser(String loginName, String name) {
			this.loginName = loginName;
			this.name = name;
		}

		public String getDeptId() {
			return deptId;
		}

		public String getRootDeptCode() {
			return rootDeptCode;
		}

		public String getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getName() {
			return name;
		}

		public String getDeptName() {
			return deptName;
		}

		public Integer getSysManager() {
			return sysManager;
		}

		public String getLastName() {
			return lastName;
		}

		public boolean isRunas() {
			return isRunas;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return name;
		}

		/**
		 * 重载hashCode,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(loginName);
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ShiroUser other = (ShiroUser) obj;
			if (loginName == null) {
				if (other.loginName != null) {
					return false;
				}
			} else if (!loginName.equals(other.loginName)) {
				return false;
			}
			return true;
		}
	}
}
